import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { EquipmentBaseEntity } from "../entities/equipment-base.entity";
import { CharacterAttributeService } from "./character-attribute.service";

@Injectable()
export class EquipmentBaseService {
  constructor(
    @InjectRepository(EquipmentBaseEntity)
    private equipmentBaseRepository: Repository<EquipmentBaseEntity>,
    private characterAttributeService: CharacterAttributeService
  ) { }

  /**
   * 获取所有装备基础数据
   */
  async findAll(): Promise<EquipmentBaseEntity[]> {
    return this.equipmentBaseRepository.find({
      order: { id: "ASC" },
    });
  }

  /**
   * 根据ID获取装备基础数据
   */
  async findById(id: number): Promise<EquipmentBaseEntity | null> {
    return this.equipmentBaseRepository.findOne({
      where: { id },
    });
  }

  /**
   * 根据基础类型获取装备列表
   */
  async findByBaseType(baseType: number): Promise<EquipmentBaseEntity[]> {
    return this.equipmentBaseRepository.find({
      where: { base: baseType },
      order: { level: "ASC" },
    });
  }

  /**
   * 根据等级获取装备列表
   */
  async findByLevel(level: number): Promise<EquipmentBaseEntity[]> {
    return this.equipmentBaseRepository.find({
      where: { level },
      order: { base: "ASC" },
    });
  }

  /**
   * 根据装备类型获取装备列表
   */
  async findByEquipmentType(type: number): Promise<EquipmentBaseEntity[]> {
    return this.equipmentBaseRepository.find({
      where: { type },
      order: { level: "ASC" },
    });
  }

  /**
   * 获取指定等级范围内的装备
   */
  async findByLevelRange(
    minLevel: number,
    maxLevel: number
  ): Promise<EquipmentBaseEntity[]> {
    return this.equipmentBaseRepository
      .createQueryBuilder("equipment")
      .where("equipment.level >= :minLevel", { minLevel })
      .andWhere("equipment.level <= :maxLevel", { maxLevel })
      .orderBy("equipment.level", "ASC")
      .addOrderBy("equipment.base", "ASC")
      .getMany();
  }

  /**
   * 根据属性需求筛选装备
   */
  async findByAttributeRequirements(
    strength: number,
    constitution: number,
    agility: number,
    intelligence: number
  ): Promise<EquipmentBaseEntity[]> {
    return this.equipmentBaseRepository
      .createQueryBuilder("equipment")
      .where("equipment.req_strength <= :strength", { strength })
      .andWhere("equipment.req_constitution <= :constitution", { constitution })
      .andWhere("equipment.req_agility <= :agility", { agility })
      .andWhere("equipment.req_intelligence <= :intelligence", { intelligence })
      .orderBy("equipment.level", "ASC")
      .getMany();
  }

  /**
   * 获取装备统计信息
   */
  async getStatistics(): Promise<{
    total: number;
    byBaseType: Record<number, number>;
    byLevel: Record<number, number>;
    byType: Record<number, number>;
  }> {
    const total = await this.equipmentBaseRepository.count();

    const baseTypeStats = await this.equipmentBaseRepository
      .createQueryBuilder("equipment")
      .select("equipment.base", "base")
      .addSelect("COUNT(*)", "count")
      .groupBy("equipment.base")
      .getRawMany();

    const levelStats = await this.equipmentBaseRepository
      .createQueryBuilder("equipment")
      .select("equipment.level", "level")
      .addSelect("COUNT(*)", "count")
      .groupBy("equipment.level")
      .getRawMany();

    const typeStats = await this.equipmentBaseRepository
      .createQueryBuilder("equipment")
      .select("equipment.type", "type")
      .addSelect("COUNT(*)", "count")
      .groupBy("equipment.type")
      .getRawMany();

    return {
      total,
      byBaseType: baseTypeStats.reduce((acc, stat) => {
        acc[stat.base] = parseInt(stat.count);
        return acc;
      }, {} as Record<number, number>),
      byLevel: levelStats.reduce((acc, stat) => {
        acc[stat.level] = parseInt(stat.count);
        return acc;
      }, {} as Record<number, number>),
      byType: typeStats.reduce((acc, stat) => {
        acc[stat.type] = parseInt(stat.count);
        return acc;
      }, {} as Record<number, number>),
    };
  }

  /**
   * 搜索装备
   */
  async search(query: string): Promise<EquipmentBaseEntity[]> {
    return this.equipmentBaseRepository
      .createQueryBuilder("equipment")
      .where("equipment.name LIKE :query", { query: `%${query}%` })
      .orWhere("equipment.intro LIKE :query", { query: `%${query}%` })
      .orderBy("equipment.level", "ASC")
      .getMany();
  }

  /**
   * 获取装备商店列表（分页）
   * 返回标准格式：{id, lvl, name, price}
   */
  async getEquipmentShopList(
    type: number = 2,
    base: number = 0,
    pageNum: number = 0,
    pageSize: number = 20
  ): Promise<{
    list: Array<{
      id: number;
      lvl: number;
      name: string;
      price: number;
    }>;
    total: number;
    page: number;
  }> {
    const queryBuilder = this.equipmentBaseRepository
      .createQueryBuilder("equipment")
      .select([
        "equipment.id",
        "equipment.level",
        "equipment.name",
        "equipment.price",
      ])
      .where("1=1");

    // 根据类型筛选
    if (type !== 0) {
      queryBuilder.andWhere("equipment.type = :type", { type });
    }

    // 根据基础类型筛选
    if (base !== 0) {
      queryBuilder.andWhere("equipment.base = :base", { base });
    }

    // 获取总数
    const total = await queryBuilder.getCount();

    // 分页查询
    const equipmentList = await queryBuilder
      .orderBy("equipment.level", "ASC")
      .addOrderBy("equipment.id", "ASC")
      .skip(pageNum * pageSize)
      .take(pageSize)
      .getMany();

    // 转换为标准格式
    const list = equipmentList.map((equipment) => ({
      id: equipment.id,
      lvl: equipment.level,
      name: equipment.name,
      price: parseInt(equipment.price) || 0,
    }));

    return {
      list,
      total,
      page: pageNum + 1,
    };
  }

  /**
   * 根据ID获取装备信息（别名方法）
   */
  async getEquipmentById(id: number): Promise<EquipmentBaseEntity | null> {
    return this.findById(id);
  }

  /**
   * 获取装备详情（用于WebSocket接口）
   * 返回格式化的装备详情数据
   */
  async getEquipmentDetail(id: number, characterId?: number): Promise<any[]> {
    const equipment = await this.findById(id);

    if (!equipment) {
      return [];
    }

    // 格式化装备详情数据，按照游戏客户端期望的格式返回
    const detailData = [
      {
        k: "名称：",
        v: equipment.name
      },
      {
        k: "图片：",
        v: equipment.image
      },
      {
        k: "等级：",
        v: equipment.level.toString()
      },
      {
        k: "负重：",
        v: equipment.weight.toString()
      },
      {
        k: "效果：",
        v: this.formatEquipmentEffects(equipment)
      },
      {
        k: "佩带条件：",
        v: await this.formatEquipmentRequirements(equipment, characterId)
      },
      {
        k: "介绍：",
        v: equipment.intro || "暂无介绍"
      }
    ];

    return detailData;
  }

  /**
   * 格式化装备效果描述
   */
  private formatEquipmentEffects(equipment: EquipmentBaseEntity): string {
    const effects = [];

    if (equipment.bonus_attack > 0) {
      effects.push(`攻击力+${equipment.bonus_attack}`);
    }
    if (equipment.bonus_defense > 0) {
      effects.push(`防御力+${equipment.bonus_defense}`);
    }
    if (equipment.bonus_hp > 0) {
      effects.push(`生命值+${equipment.bonus_hp}`);
    }
    if (equipment.bonus_mp > 0) {
      effects.push(`魔法值+${equipment.bonus_mp}`);
    }

    return effects.length > 0 ? effects.join(', ') : '无特殊效果';
  }

  /**
   * 格式化装备需求描述
   */
  private async formatEquipmentRequirements(equipment: EquipmentBaseEntity, characterId?: number): Promise<string> {
    const requirements = [];
    const statusInfo = [];

    // 获取角色属性信息
    let characterAttributes = null;
    if (characterId) {
      try {
        characterAttributes = await this.characterAttributeService.getCharacterBasicAttributes(characterId);
      } catch (error) {
        console.warn(`获取角色属性失败: ${error instanceof Error ? error.message : String(error)}`);
      }
    }

    if (equipment.req_level > 0) {
      requirements.push(`等级大于${equipment.req_level}`);
      if (characterAttributes) {
        const currentLevel = characterAttributes.lvl;
        statusInfo.push(`等级:${currentLevel}${currentLevel >= equipment.req_level ? '(可以装备)' : '(不可装备)'}`);
      }
    }
    if (equipment.req_strength > 0) {
      requirements.push(`力量大于${equipment.req_strength}`);
      if (characterAttributes) {
        const currentStrength = characterAttributes.app; // 力量属性
        statusInfo.push(`力量:${currentStrength}${currentStrength >= equipment.req_strength ? '(可以装备)' : '(不可装备)'}`);
      }
    }
    if (equipment.req_constitution > 0) {
      requirements.push(`体质大于${equipment.req_constitution}`);
      if (characterAttributes) {
        const currentConstitution = characterAttributes.hpp; // 体质属性
        statusInfo.push(`体质:${currentConstitution}${currentConstitution >= equipment.req_constitution ? '(可以装备)' : '(不可装备)'}`);
      }
    }
    if (equipment.req_agility > 0) {
      requirements.push(`敏捷大于${equipment.req_agility}`);
      if (characterAttributes) {
        const currentAgility = characterAttributes.spp; // 敏捷属性
        statusInfo.push(`敏捷:${currentAgility}${currentAgility >= equipment.req_agility ? '(可以装备)' : '(不可装备)'}`);
      }
    }
    if (equipment.req_intelligence > 0) {
      requirements.push(`智力大于${equipment.req_intelligence}`);
      if (characterAttributes) {
        const currentIntelligence = characterAttributes.mpp; // 智力属性
        statusInfo.push(`智力:${currentIntelligence}${currentIntelligence >= equipment.req_intelligence ? '(可以装备)' : '(不可装备)'}`);
      }
    }

    if (requirements.length === 0) {
      return '无特殊要求';
    }

    // 如果是均系装备（需要随机两项属性），特殊处理
    if (equipment.type === 2 && equipment.base === 5) {
      const maxReq = Math.max(equipment.req_strength, equipment.req_constitution, equipment.req_agility, equipment.req_intelligence);
      return `随机需要两项属性均大于${maxReq}`;
    }

    // 组合需求描述和状态信息
    let result = requirements.join(',');
    if (statusInfo.length > 0) {
      result += ',' + statusInfo.join(',');
    }

    return result;
  }
}
